package com.kla.power.mapper;

import com.kla.power.entity.UserEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 用户表 Mapper 接口
 * </p>
 *
 * @author WuZH
 * @since 2024-06-02
 */
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {


    @Select ( value = "<script>SELECT ui.id,ui.name,ui.roleId,ri.roleName,mi.merchantName AS merchantName,ui.telPhone,ui.email,ui.lastLoginTime FROM user_info ui LEFT JOIN merchant_info mi ON ui.merchantId=mi.id LEFT JOIN role_info ri ON ui.roleId=ri.id " +
            "<trim prefix=\"where\" prefixOverrides=\"and | or\">" +
            "<if test='userEntity.name!=null'> and ui.name=#{userEntity.name} </if>" +
            "<if test='userEntity.merchantId!=null'> and ui.merchantId=#{userEntity.merchantId} </if>" +
            "<if test='userEntity.merchantId!=null'> AND " +
            "ui.merchantId IN (SELECT id\n" +
            "                        FROM (SELECT t1.id,\n" +
            "                                     t1.parentId,\n" +
            "                                     IF(find_in_set(parentId, @pids) > 0, @pids := concat(@pids, ',', id), 0) AS ischild\n" +
            "                              FROM (SELECT id, parentId FROM merchant_info t) t1,\n" +
            "                                   (SELECT @pids:=#{userEntity.merchantId}) t2 ) t3 where ischild != 0\n" +
            "                                    UNION\n" +
            "                                    SELECT id\n" +
            "                                    FROM merchant_info pi\n" +
            "                                    WHERE pi.id=#{userEntity.merchantId})" +
            "</if> " +
            " AND ui.isUsed=1</trim> limit #{userEntity.page}, #{userEntity.limit}</script>" )
    List<UserEntity> queryList (@Param ( "userEntity" ) UserEntity userEntity );

    @Select ( value = "<script>SELECT COUNT(1) FROM user_info ui LEFT JOIN merchant_info mi ON ui.merchantId=mi.id LEFT JOIN role_info ri ON ui.roleId=ri.id " +
            "<trim prefix=\"where\" prefixOverrides=\"and | or\">" +
            "<if test='userEntity.name!=null'> and ui.name=#{userEntity.name} </if>" +
            "<if test='userEntity.merchantId!=null'> and ui.merchantId=#{userEntity.merchantId} </if>" +
            " AND ui.isUsed=1</trim></script>" )
    Integer queryCount ( @Param ( "userEntity" ) UserEntity userEntity );

}
